﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SVM;

namespace ModelPredictPro.Predict.SVM {
    public abstract class BaseSVMTask : ITask {
        #region ITask 成员

        public abstract void Run();

        public abstract IEnumerable<ITask> ReadFromTxt(string taskFileName);

        public abstract void SaveToTxt(string taskFileName);
        
        public event EventHandler<SVMStepEventArgs> StepChanged;

        #endregion

        protected BaseSVMTask() {
            
        }
        protected BaseSVMTask(string TrainSetFile, string TrainValidateFile, string TestSetFile, string ParamOutFile, string ResultOutputFile) {
            this.TrainSetFile = TrainSetFile;
            this.TrainValidateFile = TrainValidateFile;
            this.TestSetFile = TestSetFile;
            this.ParamOutFile = ParamOutFile;
            this.ResultOutputFile = ResultOutputFile;
        }

        public ISVMPredictParam Param { get; set; }
        public virtual string TrainSetFile { get; set; }
        public virtual string TestSetFile { get; set; }
        public virtual string TrainValidateFile { get; set; }
        public virtual string ParamOutFile { get; set; }
        public virtual string ResultOutputFile { get; set; }


        public Parameter SyncParams() {
            Parameter svm_parameter = new Parameter();
            svm_parameter.CacheSize = Param.CacheMemorySize;
            svm_parameter.KernelType = Param.KernelType;
            svm_parameter.Probability = Param.UseProbability;
            svm_parameter.C = Param.C;
            svm_parameter.Gamma = Param.Gamma;
            if (Param.Weights != null && Param.Weights.Count > 0) {
                foreach (var item in Param.Weights) {
                    svm_parameter.Weights.Add(item.Key, item.Value);
                }
            }
            return svm_parameter;
        }

        protected virtual void OnStepChanged(SVMStepEventArgs e) {
            if (StepChanged != null)
                StepChanged(this, e);
        }
        protected void OnStepChanged(string info, DateTime? time) {
            OnStepChanged(new SVMStepEventArgs(info, time));
        }
        protected void OnStepChanged(string info) {
            OnStepChanged(info, DateTime.Now);
        }

        protected void ValidateFileExist(string paramName, string filePath) {
            if (!File.Exists(filePath))
                throw new FileNotFoundException(string.Format("传入的 {0} 参数对应的文件路径 {1} 不存在！", paramName, filePath));
        }
        protected void ValidateNewFileCanCreated(string paramName, string filePath) {
            FileInfo file = new FileInfo(filePath);
            if (!Directory.Exists(file.Directory.FullName))
                throw new FileNotFoundException(string.Format("传入的 {0} 参数对应的文件路径 {1} 不存在！", paramName, filePath));
        }
    }
}
